//?
//1.创建axios实例对象
import router from "@/router";
import axios from "axios";
import { ElMessage } from "element-plus";
import { removeToken } from "./stores/token";
import { config } from "@/config/env.config";
import { useTokenStore } from "./stores/global";
const TOKEN_INVALID = 'Token认证失败,请重新登录'
const NETWORK_ERROR = '网络异常,请稍后再试'

export const request = axios.create({
    baseURL: config.mockApi,
    timeout: 5000,
})

//2.配置请求拦截
request.interceptors.request.use(
    config => {
        const token = useTokenStore().getToken()
        if (token) {
            config.headers['Authorization'] = `Bearer ${token}`
        }
        else {
            ElMessage.error(TOKEN_INVALID)
            setTimeout(() => {
                router.push('/')
            }, 5000)
            removeToken()
            return Promise.reject(TOKEN_INVALID)
        }
        return config
    },
    error => {
        return Promise.reject(error)
    }
)

//3.配置响应拦截
request.interceptors.response.use(
    response => {
        const { code, data, msg } = response.data
        if (code === 200) {
            console.log(response)
            return response.data
        } else if (code === 40001) {
            ElMessage.error(TOKEN_INVALID)
            setTimeout(() => {
                router.push('/')
            }, 15000)
            removeToken()
            return Promise.reject(TOKEN_INVALID)
        } else {
            ElMessage.error(msg || NETWORK_ERROR)
            return Promise.reject(msg || NETWORK_ERROR)
        }
    },
    error => {
        if (error.response?.status === 401) {
            // token 过期或无效，跳转登录
            removeToken()
            window.location.href = '/'
        }
        return Promise.reject(error)
    }
)

export default request
